import child_process from 'child_process';
import fs from 'fs';
import path from 'path';

export function build(url, moduleName) {
	const file = `def-${moduleName}.ts`;
	const shell = `npx openapi-typescript@3.4.1 ${url} -o ${file}`;
	console.log(`shell=`, shell);
	child_process.exec(shell, {cwd: path.resolve('./')}, (error, stdout, stderr) => {
		error && console.log(`[error]\n`, error);
		stdout && console.log(`[stdout]\n`, stdout);
		stderr && console.log(`[stderr]\n`, stderr);
		let content = fs.readFileSync(file, {encoding: 'utf8'});
		// 修复名称带斜杠导致的异常
		content = content.replace(/(definitions.*)"]\["/g, '$1/');
		// 修复异常定义
		content = content.replace(/definitions\["Integer"]/g, `number`);
		content = content.replace(/definitions\["List"]/g, `any[]`);
		content = content.replace(/definitions\["Page"]/g, `any`);
		content = content.replace(/definitions\["Map"]/g, `Record<string, string>`);
		// 重命名导出名
		const exportName = `${moduleName.replace(/(-)(\w)/g, (str, pre, char) => char.toUpperCase())}`;
		content = content.replace(/( )paths([ \[])/g, `$1${exportName}Paths$2`);
		content = content.replace(/( )definitions([ \[])/g, `$1${exportName}Definitions$2`);
		content = content.replace(/( )operations([ \[])/g, `$1${exportName}Operations$2`);
		// 重写文件
		fs.writeFileSync(file, content, {encoding: 'utf8'});
	});
}
